﻿using System;
using System.Collections.Generic;
using System.Text;
using OrchardSystemServer.Database;
using MySql.Data.MySqlClient;

namespace OrchardSystemServer.Security
{
    public class UserValidation
    {
        public static bool IsUserLogined(string token)
        {
            string sql = "select expiretime from usertoken where tokencontent='" + token+"'";
            string expiretime = "";
            MySQLHelper helper = new MySQLHelper();
            MySqlDataReader reader = helper.Select(sql);
            while (reader.Read())
            {
                expiretime =reader[0].ToString();
                break;
            }
            reader.Close();
            if (expiretime.Trim().Equals(""))
                return false;
            else
            {
                DateTime dateExpired = Convert.ToDateTime(expiretime);
                DateTime dateNow = DateTime.Now;
                if(dateNow.CompareTo(dateExpired)<=0)
                    return true;
                else
                    return false;
            }
        }

        public static String GetLoginToken(string username, string password)
        {
            DateTime dt = DateTime.Now.AddHours(5);//设置token过期时间为5小时
            string timeString=dt.ToString();
            string tokenSource=username+password+timeString;
            string result = SecurityUtil.Get16BitMd5(tokenSource);
            string userid=GetUserId(username,password);
            string sql = "delete from usertoken where userid ="+userid;
            MySQLHelper helper = new MySQLHelper();
            helper.Delete(sql);
            string insertSql = "insert into usertoken values( null," + userid + ",'" + result + "'" + ",'" +timeString+ "')";
            helper.Insert(insertSql);
            return result;
        }

        public static String GetUserId(string username, string password)
        {
            string sql = "select userid from user where username='"+username+"'and password='"+password+"'";
            string userid = "";
            MySQLHelper helper = new MySQLHelper();
            MySqlDataReader reader=helper.Select(sql);
            while (reader.Read())
            {
                userid = reader[0].ToString();
                break;
            }
            reader.Close();
            return userid;
        }
    }
}
